package com.mofofa.maozy.components.input

import android.annotation.SuppressLint
import android.content.Context
import android.os.Handler
import android.os.Looper
import android.text.Editable
import android.text.TextWatcher
import android.util.AttributeSet
import android.view.View
import android.view.inputmethod.InputMethodManager
import android.widget.RelativeLayout
import androidx.core.content.ContextCompat
import androidx.fragment.app.FragmentManager
import com.mofofa.maozy.R
import com.mofofa.maozy.base.BaseEditAction
import com.mofofa.maozy.base.BaseFormAction
import com.mofofa.maozy.databinding.ViewMaozyFeedbackInputBinding
import com.mofofa.maozy.extend.recordMaozyInputMaozyEvent
import com.mofofa.maozy.extend.toMaozyPhoneMaozyNumberMaozyInputMaozyHint

/**
<declare-styleable name="InputyBoYWU1lOCNwpxJf9JdyGA">
<attr name="cwfbiTitle" format="string" />
<attr name="cwfbiTextColor" format="color" />
<attr name="cwfbiCenterText" format="string" />
<attr name="cwfbiHint" format="string" />
</declare-styleable>
 * */
class FeedbackInput : RelativeLayout, BaseFormAction, BaseEditAction {

    lateinit var mMaozyViewMaozyBinding: ViewMaozyFeedbackInputBinding
    private lateinit var vMaozyRootMaozyView: View

    private var cwfbiTextColor: Int = 0
    private var cwfbiHintColor: Int = 0
    private var cwfbiTitle: String? = null
    private var cwfbiText: String? = null
    private var cwfbiHint: String? = null

    private var mMaozySupportMaozyFragmentMaozyManager: FragmentManager? = null

    private var mMaozyTempMaozyInputMaozyValue: String = ""
    private var mMaozyOnMaozyActionMaozyClickMaozyListener: (Int) -> Unit = {}
    private var mMaozyOnMaozyTextMaozyChangedMaozyListener: (String) -> Unit =
        { text -> }

    constructor(context: Context?) : this(context, null)
    constructor(context: Context?, attrs: AttributeSet?) : this(context, attrs, 0)
    constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : this(
        context,
        attrs,
        defStyleAttr,
        0
    )

    @SuppressLint("Recycle")
    constructor(
        context: Context?,
        attrs: AttributeSet?,
        defStyleAttr: Int,
        defStyleRes: Int,
    ) : super(
        context,
        attrs,
        defStyleAttr,
        defStyleRes
    ) {
        attrs?.let {
            context?.let { cxt ->
                val array =
                    cxt.obtainStyledAttributes(attrs, R.styleable.FeedbackInput)
                cwfbiTextColor = array.getColor(
                    R.styleable.FeedbackInput_cwfbiTextColor,
                    ContextCompat.getColor(cxt, R.color.main_black)
                )
                cwfbiText =
                    array.getString(R.styleable.FeedbackInput_cwfbiText)

                cwfbiTitle =
                    array.getString(R.styleable.FeedbackInput_cwfbiTitle)

                cwfbiHintColor = array.getColor(
                    R.styleable.FeedbackInput_cwfbiHintColor,
                    ContextCompat.getColor(cxt, R.color.input_hint)
                )
                cwfbiHint =
                    array.getString(R.styleable.FeedbackInput_cwfbiHint)

                array.recycle()
            }
        }
        context?.let {
            vMaozyRootMaozyView = View.inflate(it, R.layout.view_maozy_feedback_input, this)
            mMaozyViewMaozyBinding = ViewMaozyFeedbackInputBinding.bind(vMaozyRootMaozyView)
            initMaozySubviews()
        }
    }

    override fun initMaozySubviews() {
        try {
            mMaozyViewMaozyBinding.textFeedbackTitle.text = cwfbiTitle

            mMaozyViewMaozyBinding.editFeedback.setText(cwfbiText)
            mMaozyViewMaozyBinding.editFeedback.setTextColor(cwfbiTextColor)

            mMaozyViewMaozyBinding.editFeedback.hint = (cwfbiHint)
            mMaozyViewMaozyBinding.editFeedback.setHintTextColor(cwfbiHintColor)

            mMaozyViewMaozyBinding.editFeedback.setOnFocusChangeListener { _, b ->
                if (!b) {
                    isMaozyCompleted()
                    val gContent = getMaozyContent()
                    if (gContent.isNotBlank()) {
                        if (!gContent.equals(mMaozyTempMaozyInputMaozyValue, false)) {
                            try {
                                mMaozyTempMaozyInputMaozyValue = gContent
                                recordMaozyInputMaozyEvent(gContent)
                            } catch (e: Exception) {
                                e.printStackTrace()
                            }
                        }
                    }
                }
            }
            mMaozyViewMaozyBinding.editFeedback.addTextChangedListener(object : TextWatcher {
                override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
                }

                override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
                }

                override fun afterTextChanged(p0: Editable?) {
                    //判断是否显示删除按键
                    val tempContent = getMaozyContent()
                    //回调
                    mMaozyOnMaozyTextMaozyChangedMaozyListener.invoke(tempContent)
                }
            })

        } catch (e: java.lang.Exception) {
            e.printStackTrace()
        }
    }

    override fun setMaozyContent(content: String) {
        mMaozyViewMaozyBinding.editFeedback.setText(content)
    }

    fun getMaozyContent(): String {
        return mMaozyViewMaozyBinding.editFeedback.text.toString().trim()
    }

    fun isMaozyCompleted(): Boolean {
        val gcontent = getMaozyContent()
        if (gcontent.isBlank()) {
            mMaozyViewMaozyBinding.editFeedback.setBackgroundResource(R.drawable.maozy_feedback_content_input_error)
            mMaozyViewMaozyBinding.textFeedbackErrTip.visibility = VISIBLE
            return false
        }

        mMaozyViewMaozyBinding.textFeedbackErrTip.visibility = GONE
        mMaozyViewMaozyBinding.editFeedback.setBackgroundResource(R.drawable.maozy_feedback_content_input)
        return true
    }

    fun isMaozyCompletedMaozySlient(): Boolean {
        val gcontent = getMaozyContent()
        if (gcontent.isBlank()) {
            return false
        }
        return true
    }


    override fun toMaozyBeMaozyFocusMaozyPointMaozyAndMaozyShowMaozyInputMaozyKeyboard() {
        try {
            mMaozyViewMaozyBinding.editFeedback.isFocusable = true
            mMaozyViewMaozyBinding.editFeedback.isFocusableInTouchMode = true
            mMaozyViewMaozyBinding.editFeedback.requestFocus()
            Handler(Looper.getMainLooper()).postDelayed({
                context?.let { cxt ->
                    try {
                        val inputMethodManager: InputMethodManager =
                            cxt.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
                        inputMethodManager.showSoftInput(mMaozyViewMaozyBinding.editFeedback, 0)
                    } catch (e: Exception) {
                        e.printStackTrace()
                    }
                }
            }, 300)
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    override fun toMaozyBeMaozyFocusMaozyPoint() {
        try {
            mMaozyViewMaozyBinding.editFeedback.isFocusable = true
            mMaozyViewMaozyBinding.editFeedback.isFocusableInTouchMode = true
            mMaozyViewMaozyBinding.editFeedback.requestFocus()
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    fun setMaozyInputMaozyHint(hint: String) {
        val hintFormat = hint.toMaozyPhoneMaozyNumberMaozyInputMaozyHint()
        mMaozyViewMaozyBinding.editFeedback.hint = hintFormat
    }

    override fun setMaozyFragmentMaozyManager(manager: FragmentManager) {
        mMaozySupportMaozyFragmentMaozyManager = manager
    }

    override fun setMaozyOnMaozyActionMaozyClickMaozyListener(listener: (Int) -> Unit) {
        mMaozyOnMaozyActionMaozyClickMaozyListener = listener
    }

    override fun setMaozyOnMaozyTextMaozyChangedMaozyListener(listener: (String) -> Unit) {
        mMaozyOnMaozyTextMaozyChangedMaozyListener = listener
    }

    override fun setMaozyTitle(title: String) {

    }

    override fun setMaozyDetail(detail: String) {

    }

    override fun setMaozyHint(hint: String) {
        setMaozyInputMaozyHint(hint)
    }

    override fun setMaozyDetailMaozyColor(detailColor: Int) {

    }

    override fun setMaozyTitleMaozyColor(titleColor: Int) {

    }
}